package com.xiaobo.framework.service;

import com.xiaobo.framework.common.exception.BizException;
import com.xiaobo.framework.kits.RegexKits;
import com.xiaobo.framework.kits.RsaKits;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.ClassUtils;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.nio.charset.StandardCharsets;

/**
 * @author: <a href="get_xiaobo@163.com">Josh_Xu</a>
 * @description:
 * @create: 2020-08-19 15:26
 **/
@Component
public class SecretKeyAuth {

    private static final Logger logger = LoggerFactory.getLogger(SecretKeyAuth.class);

    /**
     * 放弃治疗的写法
     * @return
     * @throws ClassNotFoundException
     * @throws NoSuchMethodException
     * @throws IllegalAccessException
     * @throws InstantiationException
     * @throws InvocationTargetException
     */
    @Deprecated
    public String authPublicKey() throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InstantiationException, InvocationTargetException {
        ClassLoader classLoader = SecretKeyAuth.class.getClassLoader();
        if (!ClassUtils.isPresent("com.xiaobo.framework.kits.RsaKits", classLoader)) {
            logger.error("类加载失败{}", classLoader);
            throw new BizException("服务端加载异常");
        }
        Class<?> clazz = Class.forName("com.xiaobo.framework.kits.RsaKits");
        Method publicKey = clazz.getDeclaredMethod("getPublicKey",null);
        publicKey.setAccessible(true);
        String invoke = (String) publicKey.invoke(clazz.getDeclaredConstructor().newInstance());
        return invoke;

    }

    public  String getPublicKey() throws IOException {
        InputStream inputStream = RsaKits.class.getClassLoader().getResourceAsStream("META-INF/default-public.pem");
        BufferedInputStream bis = new BufferedInputStream(inputStream, 1024);
        int length = 0;
        StringBuilder stringBuilder = new StringBuilder();
        byte[] buffer = new byte[1024];
        while ((length = bis.read(buffer)) != -1) {
            stringBuilder.append(new String(buffer, 0, length, StandardCharsets.UTF_8));
        }
        String key = stringBuilder.toString();
        try {
            String publicKey = RegexKits.loadPublicKey(key);
            return publicKey;
        } catch (Exception e) {
            throw new BizException("公钥加载失败!");
        }
    }


}
